<?php
/**
 * （国内）库存入库明细 （(国内)采购收货入库记录明细）
 * (model)
 */

namespace App\Models\Inventory;

use App\Models\Product\ProductClassify;
use App\Models\Product\ProductSku;
use App\Models\Purchase\PurchaseOrderDetail;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Query\Builder;
use Illuminate\Support\Facades\DB;

class StoragePurDetail extends Model
{
    protected $table = 'in_storage_detail';

    protected $guarded = [];

    /**
     * 关联库（国内）存入库记录
     * @return \Illuminate\Database\Eloquent\Relations\BelongsTo
     */
    public function storage(){
        return $this->belongsTo(Storage::class,'storage_no','storage_no');
    }

    /**
     * 关联采购单明细
     * @return \Illuminate\Database\Eloquent\Relations\BelongsTo
     */
    public function poDetail(){
        return $this->belongsTo(PurchaseOrderDetail::class,'detail_id');
    }

    public function sku(){
        return $this->belongsTo(ProductSku::class,'psku_id');
    }

    public function skuClassify(){
        return $this->hasOneThrough(
            ProductClassify::class,
            ProductSku::class,
            'id',//中间表
            'id',//目标表
            'psku_id',//当前模型
            'classify_id'//中间表
        );
    }

    /**
     * 收货入库明细汇总
     * @param $filters
     * @return Model|Builder|object|null
     */
    public static function getStoragePurDetailTotal($filters){
        $query = DB::table('in_storage_detail as sd')
            ->leftJoin('in_storage as s','sd.storage_no', '=', 's.storage_no')
            ->leftJoin('purchase_order_detail as pod','sd.detail_id','=','pod.id')
            ->leftJoin('product_sku as ps','sd.psku_id','=','ps.id')
            ->leftJoin('product_classify as pc','ps.classify_id','=','pc.id')
            ->where('s.type',Storage::TYPE_RECEIVE)//收货入库
            ->selectRaw('SUM(IFNULL(pod.order_num, 0)) as order_num,
                    SUM(IFNULL(sd.storage_num, 0)) as storage_num,
                    SUM(IFNULL(sd.supplier_price, 0)) as supplier_price,
                    SUM(IFNULL(sd.storage_num, 0) * IFNULL(sd.supplier_price, 0)) as supplier_amount,
                    SUM(IFNULL(sd.unit_price,0)) as unit_price,
                    SUM(IFNULL(sd.unit_price_no_tax,0)) as unit_price_no_tax,
                    SUM(IFNULL(sd.pack_price,0)) as pack_price,
                    SUM(IFNULL(sd.storage_num, 0) * IFNULL(sd.unit_price, 0)) as amount');
        $query = StorageDetail::formatFilters($query,$filters);
        return $query->first();
    }
}
